{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "54c0e233",
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "# The Base Classification Model\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3d1c1bb6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T20:14:31.464177Z",
     "iopub.status.busy": "2023-08-18T20:14:31.463903Z",
     "iopub.status.idle": "2023-08-18T20:14:31.468562Z",
     "shell.execute_reply": "2023-08-18T20:14:31.467672Z"
    },
    "origin_pos": 13,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "from d2l import torch as d2l\n",
    "\n",
    "class Classifier(d2l.Module):  \n",
    "    \"\"\"The base class of classification models.\"\"\"\n",
    "    def validation_step(self, batch):\n",
    "        Y_hat = self(*batch[:-1])\n",
    "        self.plot('loss', self.loss(Y_hat, batch[-1]), train=False)\n",
    "        self.plot('acc', self.accuracy(Y_hat, batch[-1]), train=False)\n",
    "\n",
    "@d2l.add_to_class(d2l.Module)  \n",
    "def configure_optimizers(self):\n",
    "    return torch.optim.SGD(self.parameters(), lr=self.lr)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "38d43632",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "Compare the predicted class with the ground truth `y` elementwise"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "b132abd8",
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "9"
    },
    "execution": {
     "iopub.execute_input": "2023-08-18T20:14:31.471739Z",
     "iopub.status.busy": "2023-08-18T20:14:31.471463Z",
     "iopub.status.idle": "2023-08-18T20:14:31.477124Z",
     "shell.execute_reply": "2023-08-18T20:14:31.476264Z"
    },
    "origin_pos": 17,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "@d2l.add_to_class(Classifier)  \n",
    "def accuracy(self, Y_hat, Y, averaged=True):\n",
    "    \"\"\"Compute the number of correct predictions.\"\"\"\n",
    "    Y_hat = Y_hat.reshape((-1, Y_hat.shape[-1]))\n",
    "    preds = Y_hat.argmax(axis=1).type(Y.dtype)\n",
    "    compare = (preds == Y.reshape(-1)).type(torch.float32)\n",
    "    return compare.mean() if averaged else compare"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Slideshow",
  "language_info": {
   "name": "python"
  },
  "required_libs": [],
  "rise": {
   "autolaunch": true,
   "enable_chalkboard": true,
   "overlay": "<div class='my-top-right'><img height=80px src='http://d2l.ai/_static/logo-with-text.png'/></div><div class='my-top-left'></div>",
   "scroll": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}